package Logic;
import Core.*;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.lmax.disruptor.util.DaemonThreadFactory;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import microgame.airplane.proto.Login;
import microgame.airplane.proto.MsgTypeOuterClass;
import microgame.airplane.proto.ProtoPacker;
import microgame.toolset.datatable.DataTableManager;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

public class Business extends Thread {

    @Override
    public void run() {

        try {
            DataTableManager.Instance().Init();
        } catch (Exception e) {
            Log4j2.LOGGER.error(e.toString());
        }

        ClientManager.Instance().Init();
        MatchManager.Instance().Init();
        PropDataTemplate.Instance().Init();

        while (true) {
            try {
                // network data
                ProcessNetData();

                // 业务逻辑
                MatchManager.Instance().Update();

                Thread.sleep(30);
            } catch (Exception ie) {
                Log4j2.LOGGER.error(ie.toString());
            }
        }
    }

    private void ProcessNetData() throws Exception {
        NetData nd;
        while ((nd = (NetData) NetDataQueue.Instance().getQueue().poll(1, TimeUnit.NANOSECONDS)) != null) {
            int id = nd.GetId();
            if (id < 90000) {
                // 0 to 90000 is protobuf message
                ProtoCenter.Dispatch(id, nd);
            } else {
                // above 90000 is custome message(command)
                if (id == 90000) {
                    ClientManager.Instance().Remove(nd.GetClientId());
                    Log4j2.LOGGER.info("Client quit.");
                }
            }
        }
    }
}
